﻿import { Col, Input, Row, Upload, Button, Modal, Menu, Card, Empty } from "antd"
import { useEffect, useContext, useState } from "react";
import { AppStateContext } from "../store/context";
import ImgCrop from "antd-img-crop";
import axios from "axios";
import { message } from "antd";

const { Meta } = Card

const VideoHeader = () => {
  // const [plateNum, setPlateNum, faceList, setFaceList] = usePlateAndFace();
  const { plateNum, setPlateNum, faceList, setFaceList } = useContext(AppStateContext);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modelList, setModelList] = useState([]);
  const [current, setCurrent] = useState('carplate');
  const [faceData, setFaceData] = useState([]);
  const [carData, setCarData] = useState([]);

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const onFaceChange = (info) => {
    setFaceList(info.fileList);
    console.log(info.fileList);
    // info.file.status = 'done';
    // setTimeout(() => {
    //   info.file.status = 'done';
    // }, 500)
  };
  const beginDetect = async () => {
    // 声明formData
    let res, res1
    if (faceList.length > 0) {
      const formData = new FormData();
      // formData.append("plateNum", plateNum);
      console.log(faceList);
      formData.append("image", faceList[0].response);
      formData.append("video_id", String(localStorage.getItem("video_id")));
      formData.append("confidence", String(0.85));
      // 发送请求
      res = await axios.post("http://192.168.14.144:5000/search_face", formData)
      console.log(res);
      if (res.status === 200) {
        res.data.sort((a, b) => a.timestamp - b.timestamp);
        setFaceData(res.data);
        // message.success('检索成功')
      }
    }

    if (plateNum !== '') {
      const formData1 = new FormData();
      formData1.append("video_id", String(localStorage.getItem("video_id")));
      formData1.append("license_plate", plateNum);
      res1 = await axios.post("http://192.168.14.144:5000/search_lp", formData1)
      console.log(res1);
      if (res1.status === 200) {
        res1.data.sort((a, b) => a.timestamp - b.timestamp);
        setCarData(res1.data);
        // message.success('检索成功')
      }
    }
    if (faceList.length > 0 && plateNum !== '') {
      if (res.status === 200 && res1.status === 200) {
        message.success('检索成功')
        showModal()
      }
      else {
        message.error('检索失败')
      }
    }
    else if (faceList.length > 0) {
      if (res.status === 200) {
        message.success('检索成功')
        showModal()
      }
      else {
        message.error('检索失败')
      }
    }
    else if (plateNum !== '') {
      if (res1.status === 200) {
        message.success('检索成功')
        showModal()
      }
      else {
        message.error('检索失败')
      }
    }
    
  }
  return (
    <Row gutter={[0, 20]} style={{
      width: "93.5%",
      padding: "10px 10px",
    }}>
      <p>检测中的车牌</p>
      <Col span={24}>
        {/* <span>车牌号：</span> */}
        <Input placeholder="待检索车牌号" variant="filled" value={plateNum}
          onChange={(e) => setPlateNum(e.target.value)} style={{

          }}
        />
      </Col>

      <Col span={24}>
        <ImgCrop>
          <Upload

            // action="https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload"
            customRequest={({ file, onSuccess }) => {
              setTimeout(() => {
                // file.status = 'done';
                // file.response = {};
                onSuccess(file)
                // 更新文件列表
                // setFaceList([...faceList, file]);

              }, 1000);
            }}
            onChange={onFaceChange}
            listType="picture-card"
            fileList={faceList}
            // onChange={onChange}
            // onPreview={onPreview}
            style={{
              width: "50px",
              height: "50px"
            }}
          >
            {/* {fileList.length < 5 && '+ Upload'} */}
            +上传人脸
          </Upload>
        </ImgCrop>
      </Col>
      <Col span={24}>
      <Button style={{
        width: "100%",
      }} type="primary" onClick={beginDetect}>开始检测</Button>
      </Col>
      <Modal title={'检索结果'} open={isModalOpen} width={600} style={{
        // height: 500,
        overflow: 'auto'
      }}
        onCancel={handleCancel}
        onOk={handleOk}
      >
        <Menu
          onClick={(e) => {
            console.log('click ', e);
            setCurrent(e.key);
          }}
          mode="horizontal"
          items={[
            {
              label: '车牌检索结果',
              key: 'carplate',
            },
            {
              label: '人脸检索结果',
              key: 'face',
            }
          ]}
          style={{
            paddingBottom: 20
          }}
        // selectedKeys={}
        ></Menu>
        {
          current === 'carplate' ?
            carData.length > 0 ? carData.map((item) => {
              return (
                <Card cover={
                  <img width={'100%'} height={300} style={{
                    objectFit: 'contain',
                    height: 300
                  }} src={item.url}></img>
                }>
                  <Meta title={item.timestamp + 's'}></Meta>
                </Card>
              )
            }) : <Empty/> :
            faceData.length > 0 ? faceData.map((item) => {
              return (
                <Card cover={
                  <img src={item.url} style={{
                    objectFit: 'contain',
                    height: 200
                  }}></img>
                }>
                  <Meta title={item.timestamp + 's'}></Meta>
                </Card>
              )
            }) : <Empty/>
        }
      </Modal>
    </Row>
  )
}

export default VideoHeader;